import SearchSuggestions from '@/components/SearchSuggestions';
import { useAppSelector } from '@/utils/hooks';
import { useEffect, useState } from 'react';
import styles from './styles.module.less'
const Search = () => {
  const {
    currentSearchEngines,
  } = useAppSelector((state) => state.appConfig);
  const [value, setValue] = useState('');
  const [focus, setFocus] = useState(false);

  const openNewTab = (search: string) => {
    window.open(`${currentSearchEngines.url}${search}`)
  }

  useEffect(() => {
    document.addEventListener('click', () => {
      setValue('')
    })
  }, [])

  return (
    <div className={styles.Search}>
      <input
        type="text"
        aria-label='conciseModeSearch'
        className={styles.conciseModeInput}
        value={value}
        onChange={(e) => {
          setValue(e.target.value)
        }}
        onFocus={() => {
          setFocus(true)
        }}
        onClick={(e) => {
          e.stopPropagation();
        }}
        onKeyDown={(e) => {
          if (e.code === "Enter") {
            openNewTab(value)
            setValue('')
          } else {
          }
        }}
      />
      {focus && (
        <SearchSuggestions
          absolute
          searchValue={value}
          itemClick={() => {
            setValue('')
          }}
        />
      )}
    </div>
  )
}
export default Search